package com.ai.bitcoin.weixin;

import com.ai.bitcoin.service.helper.WeiXinPayServiceHelper;
import com.ai.bitcoin.service.helper.WeiXinPayServiceHelper.WeiXinPayResult;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;





/**
 *
 * @author xd
 *
 * @param <T>
 */
public class WeixinDom extends BaseDom<WeiXinPayResult> {

    private static final Logger logger = LoggerFactory.getLogger(WeixinDom.class);

    //	private static final String ROOT_NODE = "xml";
    private static final String RETURN_CODE = "return_code";
    private static final String RETURN_MSG = "return_msg";
    private static final String RESULT_CODE = "result_code";
    private static final String ERROR_CODE = "err_code";
    private static final String ERROR_CODE_DES = "err_code_des";
    private static final String TRADE_TYPE = "trade_type";
    private static final String PREPAY_ID = "prepay_id";
    private static final String CODE_URL = "code_url";


    @Override
    public  WeiXinPayResult parserXml(String xml) {

        if (StringUtils.isBlank(xml)) {
            return null;
        }

        SAXBuilder saxBuilder = new SAXBuilder();
        saxBuilder.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
        saxBuilder.setFeature("http://xml.org/sax/features/external-general-entities", false);
        saxBuilder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        Document document = null;

        try {
            document = saxBuilder.build(new StringReader(xml));
        } catch (JDOMException e) {
            logger.error("input dom string occured error", e);
        } catch (IOException e) {
            logger.error("input io occured error", e);
        }

        if (document != null) {
            Element root = document.getRootElement();
            if (root != null ) {
                List<Element> childrens = root.getChildren();
                if (childrens != null && !childrens.isEmpty()) {
                    WeiXinPayResult weiXinPayResult = new WeiXinPayResult();
                    for (Element element : childrens) {
                        String elementName = element.getName();
                        switch (elementName) {
                            case RETURN_CODE:
                                weiXinPayResult.setReturn_code(element.getValue());
                                break;
                            case RETURN_MSG:
                                weiXinPayResult.setReturn_msg(element.getValue());
                                break;
                            case RESULT_CODE:
                                weiXinPayResult.setResult_code(element.getValue());
                                break;
                            case ERROR_CODE:
                                weiXinPayResult.setErr_code(element.getValue());
                                break;
                            case ERROR_CODE_DES:
                                weiXinPayResult.setErr_code_des(element.getValue());
                                break;
                            case TRADE_TYPE:
                                weiXinPayResult.setTrade_type(element.getValue());
                                break;
                            case PREPAY_ID:
                                weiXinPayResult.setPrepay_id(element.getValue());
                                break;
                            case CODE_URL:
                                weiXinPayResult.setCode_url(element.getValue());
                            default:
                                break;
                        }

                    }

                    return weiXinPayResult;
                }

            }

        }

        return null;
    }

    @Override
    public String createXml(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Document document = new Document();
        Element rootElement = new Element("xml");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Element element = new Element(entry.getKey());
            element.setText(String.valueOf(entry.getValue()));
            rootElement.addContent(element);
        }
        document.addContent(rootElement);
        ByteArrayOutputStream byteRsp = new ByteArrayOutputStream();
        XMLOutputter xmlOut = new XMLOutputter();
        try {
            xmlOut.output(document, byteRsp);
        } catch (Exception e) {
            logger.error("output xml occured error", e);
        }
        return byteRsp.toString();
    }


    public static void main(String[] args) {

        /**
         * test code
         */
//		StringBuilder xml = new StringBuilder("<xml>");
//		xml.append("<return_code><![CDATA[SUCCESS]]></return_code>");
//		xml.append("<return_msg><![CDATA[OK]]></return_msg>");
//		xml.append("<result_code><![CDATA[SUCCESS]]></result_code>");
//		xml.append("<prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>");
//		xml.append("<trade_type><![CDATA[JSAPI]]></trade_type>").append("</xml>");
//
//		BaseDom<WeiXinPayResult> baseDom = new WeixinDom();
//		WeiXinPayResult weiXinPayResult = baseDom.parserXml(xml.toString());
//		System.out.print("return_code-->"+weiXinPayResult.getReturn_code());

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("aaa", 1234);
        map.put("wer", "hahe");

        BaseDom<WeiXinPayResult> baseDom = new WeixinDom();
        String xml = baseDom.createXml(map);
        System.out.print("xml-->"+xml);
    }



}
